package com.dev.weixin.manager.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.dev.security.util.DataGrid;
import com.dev.weixin.manager.beans.ImageSource;
import com.dev.weixin.manager.dao.ImageSourceRepository;
import com.dev.weixin.manager.service.IImageSourceService;
import com.dev.weixin.utils.ObjectUtils;

/**
 * @author 飘渺青衣
 * @see
 */
@Service
public class ImageSourceService implements IImageSourceService {
	
	private static final Logger LOG = LogManager.getLogger(ImageSourceService.class);

	@Autowired
	private ImageSourceRepository imageSourceRepository;
	
	/* (non-Javadoc)
	 * @see com.dev.weixin.manager.service.IImageSourceService#save(com.dev.weixin.manager.beans.ImageSource)
	 */
	@Override
	public void save(ImageSource image) {
		ObjectUtils.trimToEmpty(image);
		this.imageSourceRepository.save(image);
	}

	/* (non-Javadoc)
	 * @see com.dev.weixin.manager.service.IImageSourceService#update(java.lang.String, java.lang.String)
	 */
	@Override
	public boolean update(String id, String user_id, String media_id) {
		return this.imageSourceRepository.update(
				StringUtils.trimToEmpty(id), 
				StringUtils.trimToEmpty(user_id),
				StringUtils.trimToEmpty(media_id)) > 0;
	}

	/* (non-Javadoc)
	 * @see com.dev.weixin.manager.service.IImageSourceService#remove(java.lang.String)
	 */
	@Override
	public void remove(String id, String user_id) {
		this.imageSourceRepository.delete(
				StringUtils.trimToEmpty(id),
				StringUtils.trimToEmpty(user_id));
	}

	/* (non-Javadoc)
	 * @see com.dev.weixin.manager.service.IImageSourceService#remove(java.lang.String[])
	 */
	@Override
	public int remove(String[] ids, String user_id) {
		return this.imageSourceRepository.delete(ids, StringUtils.trimToEmpty(user_id));
	}

	/* (non-Javadoc)
	 * @see com.dev.weixin.manager.service.IImageSourceService#findPage(int, int)
	 */
	@Override
	public DataGrid<ImageSource> findPage(String type, String user_id, int page, int size) {
		Sort sort = new Sort(new Order(Direction.DESC, "createtime"));
		return new DataGrid<ImageSource>(
				this.imageSourceRepository.findPage(
						StringUtils.trimToEmpty(type),
						StringUtils.trimToEmpty(user_id),
						new PageRequest(page > 0 ? page - 1 : 0, size, sort)));
	}

	/* (non-Javadoc)
	 * @see com.dev.weixin.manager.service.IImageSourceService#upload(java.lang.String, java.lang.String, java.lang.String, org.springframework.web.multipart.MultipartFile[])
	 */
	@Override
	public int upload(
			String type, String user_id, String dir,
			String path, MultipartFile file) {
		String t_dir = dir.endsWith(File.separator) ? dir : 
			new StringBuilder().append(dir).append(File.separator).toString();
		int count = 0;
		if(file != null) {
			if(!file.isEmpty()) {
				ImageSource image = new ImageSource();
				image.setName(file.getOriginalFilename());
				image.setContentType(file.getContentType());
				image.setCreatetime(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss"));
				image.setType(StringUtils.trimToEmpty(type));
				image.setUser_id(user_id);
				String filename = new StringBuilder().append(UUID.randomUUID())
							.append(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."))).toString();
				image.setPath(new StringBuilder().append(path).append(filename).toString());
				File dirs = new File(t_dir);
				if(!dirs.exists()) {
					dirs.mkdirs();
				}
				FileOutputStream fos = null;
				InputStream is = null;
				byte[] buff = new byte[8192];
				int len = 0;
				try {
					is = file.getInputStream();
					fos = new FileOutputStream(new StringBuilder().append(t_dir).append(filename).toString());
					while((len = is.read(buff)) > 0) {
						fos.write(buff, 0, len);
					}
					this.imageSourceRepository.save(image);
				} catch (FileNotFoundException e) {
					LOG.error("未找到文件！", e);
				} catch (IOException e) {
					LOG.error("获取输入流异常！", e);
				} finally {
					IOUtils.closeQuietly(is);
					IOUtils.closeQuietly(fos);
				}
				count ++;
			}
		}
		return count;
	}

}
